from functools import wraps
from flask import session,redirect,url_for,request,abort
import os
import uuid
from datetime import datetime
from app.models import Admin,Role,Auth

def admin_login_require(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if session.get('login_admin', None) is None:
            # 如果session中未找到该键，则用户需要登录
            return redirect(url_for('admin.login', next=request.url))
        return func(*args, **kwargs)
    return decorated_function


# 权限控制装饰器
def permission_control(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        login_admin = Admin.query.join(
            Role
        ) .filter(
            Role.id == Admin.role_id,
            Admin.name == session['login_admin']
        ).first()

        all_auth = Auth.query.all()  # 数据库所有权限

        auths = login_admin.role.auths
        # 用户权限id列表
        auths = list(map(lambda item:item,auths.split(',')))
        urls = [auth.url for auth in all_auth for admin_auth_id in auths if admin_auth_id == auth.id]
        rule = request.url_rule
        #权限不存在，且不是超级管理员
        if str(rule) not in urls and login_admin.is_super != 0:
            abort(401)
        return func(*args, **kwargs)
    return decorated_function


# 要求登录才能访问
def user_login_require(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        if session.get('login_user', None) is None:
            # 如果session中未找到该键，则用户需要登录
            return redirect(url_for('home.login', next=request.url))
        return func(*args, **kwargs)
    return decorated_function


# 修改文件名称
def change_filename(filename):
    fileinfo = os.path.splitext(filename)  # 分离包含路径的文件名与包含点号的扩展名
    filename = datetime.now().strftime("%Y%m%d%H%M%S") + str(uuid.uuid4().hex + fileinfo[-1])
    # print('函数中修改后的文件名：', filename)
    return filename